package org.example.erp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.erp.domain.Process;
import org.example.erp.domain.Workshop;
import org.example.erp.service.WorkshopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api")
public class WorkshopController {
    @Autowired
    WorkshopService workshopService;

    @GetMapping("/workshopSetup/find")
    public DataResult find(
            @RequestParam(value = "workshopCode",required = false) String workshopCode,
            @RequestParam(value = "workshopName",required = false) String workshopName,
            @RequestParam(value = "currentPage", defaultValue = "1") Integer currentPage,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize
    ) {
        // 检查所有查询参数是否为空
        boolean allParamsEmpty = (workshopCode == null || workshopCode.isEmpty()) &&
                (workshopName == null || workshopName.isEmpty()) && (currentPage == -1 && pageSize == -1);

        Page<Workshop> page = new Page<>(currentPage, pageSize);
        QueryWrapper<Workshop> queryWrapper = new QueryWrapper();
        if (workshopCode != null && !workshopCode.isEmpty()) {
            queryWrapper.lambda().like(Workshop::getWorkshopCode, workshopCode);
        }
        if (workshopName != null && !workshopName.isEmpty()) {
            queryWrapper.lambda().like(Workshop::getWorkshopName, workshopName);
        }
        if (allParamsEmpty) {
            // 不使用分页查询
            return DataResult.success(workshopService.list(queryWrapper));
        } else {
            // 使用分页查询
            page = workshopService.page(page, queryWrapper);
            return DataResult.success(page);
        }
    }

    @PostMapping("/workshopSetup/insert")
    public DataResult insert(@RequestBody Workshop workshop) {
        boolean save = workshopService.save(workshop);
        return DataResult.success(save ? "成功" : "失败");
    }

    @PutMapping("/workshopSetup/update")
    public DataResult update(@RequestBody Workshop workshop) {
        boolean update = workshopService.updateById(workshop);
        return DataResult.success(update ? "成功" : "失败");
    }

    @DeleteMapping("/workshopSetup/delete")
    public DataResult delete(@RequestBody List<String> id) {
        boolean removeByIds = workshopService.deleteDetails(id);
        return DataResult.success(removeByIds ? "成功" : "失败");
    }
}
